package com.rtx.wms.customer.ris.transfer;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rtx.edi.model.api.bo.ApiMappingInfoBo;
import com.rtx.edi.model.base.Constant;
import com.rtx.wms.std.transer.bean.ApiTransfer;
import com.rtx.wms.std.transer.service.ApiTransferService;

import cn.hutool.core.util.StrUtil;

/**
 * 内部转移单中间表
 */
@Component
public class EdiTransferHandler {
	
    private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	ApiTransferService apiTransferService;
	
	@Autowired
	CallRisTransfer callRisTransfer;
	
    public void handlerTransfer(ApiMappingInfoBo bo){
        //获取中间表未处理成功的订单
        List<ApiTransfer> list = selectApidata("ris_edi");
        if(CollectionUtils.isEmpty(list)){
            return;
        }
        for(ApiTransfer o : list){
            //添加wms出库单
        	callRisTransfer.callRisWMSAPI(o, bo);;
            //更新中间表状态
            updateStatus("ris_edi",o);
        }
    }
    
    //获取待处理单据
    protected List<ApiTransfer> selectApidata(String datasourcekey) {
    	LambdaQueryWrapper<ApiTransfer> qw = Wrappers.lambdaQuery();
    	qw.eq(ApiTransfer::getCallristransferflag, Constant.DEFAULT_FLAG);
    	return apiTransferService.queryWithDetailByCondition(datasourcekey, qw);
    };
    
    
    
    
    /**
     * 更新中间表
     * @param whseid
     * @param apiOrders
     */
    private void updateStatus(String whseid,ApiTransfer at) {
        LambdaUpdateWrapper<ApiTransfer> update = Wrappers.lambdaUpdate();
        update.eq(ApiTransfer::getSerialkey,at.getSerialkey())
                .set(ApiTransfer::getCallristransferflag,at.getCallristransferflag())
                .set(StringUtils.hasText(at.getCallristransfermsg()),ApiTransfer::getCallristransfermsg,StrUtil.sub(at.getCallristransfermsg(),0,200));
        apiTransferService.updApiTransferStatus(whseid, update);
    }
}
